﻿using System.Collections;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// UGUI CanvasGroup 类扩展
/// </summary>
public static class CanvasGroupExtension
{

    /// <summary>
    /// 设置可视状态
    /// </summary>
    /// <param name="canvasGroup"></param>
    /// <param name="isActive"></param>
    public static void SetActive(this CanvasGroup canvasGroup, bool isActive)
    {
        canvasGroup.alpha = isActive ? 1 : 0;
        canvasGroup.interactable = isActive;
        canvasGroup.blocksRaycasts = isActive;
    }

    /// <summary>
    /// 透明度渐变
    /// </summary>
    /// <param name="canvasGroup"></param>
    /// <param name="alpha"></param>
    /// <param name="duration"></param>
    /// <returns></returns>
    public static IEnumerator FadeToAlpha(this CanvasGroup canvasGroup, float alpha, float duration)
    {
        float time = 0f;
        float originalAlpha = canvasGroup.alpha;
        while (time < duration)
        {
            time += Time.deltaTime;
            canvasGroup.alpha = Mathf.Lerp(originalAlpha, alpha, time / duration);
            yield return Utility.Coroutine.WaitForEndOfFrame;
        }

        canvasGroup.alpha = alpha;
    }
}
